import 'package:xiaomi_shop/app/services/storage.dart';
import 'package:xiaomi_shop/models/shopModel.dart';

class CartService {
  // 获取购物车中的商品
  static Future<List<ShopModel>> getCartData() async {
    List? list = await Storage.getData("CART_SHOP_LIST");
    if (list != null) {
      return list.map((e) => ShopModel.fromJson(e)).toList();
    } else {
      return [];
    }
  }

  // 购物车添加商品
  static Future<bool> addShop2Cart(ShopModel model) async {
    List<ShopModel> list = await getCartData();
    if (list.isNotEmpty) {
      bool hasData = list.any((element) => element.id == model.id);
      if (hasData) {
        ShopModel item = list.singleWhere((element) => element.id == model.id);
        list.remove(item);
        item.buyNumber += model.buyNumber;
        list.add(item);
        return Storage.setData("CART_SHOP_LIST", list);
      } else {
        list.add(model);
        return Storage.setData("CART_SHOP_LIST", list);
      }
    } else {
      list.add(model);
      return Storage.setData("CART_SHOP_LIST", list);
    }
  }

  // 删除购物车中的商品
  static void deleteShop(ShopModel model) async {
    List<ShopModel> list = await getCartData();
    list.remove(model);
    Storage.setData("CART_SHOP_LIST", list);
  }
}
